import re
from realinplaceedit.models import Page, Change
from realinplaceedit.utils import json_encode

def changes(request):
    meta = request.META
    changes = []
    containers = []
    if meta and request.user.is_authenticated():
        path_info = meta.get('PATH_INFO', None)
	page = Page.objects.filter(url=path_info) or get_page_pattern(path_info)
	if page:
	    page = page[0]
	    containers = page.container_set.all()
	    changes = Change.objects.filter(container_user__container__in=containers, container_user__user=request.user)
    
    changes_json = json_encode(changes)
    containers_json = json_encode(containers, False, 1) 
    return {'changes':changes_json,'containers':containers_json}

def get_page_pattern(path):
    pages_pattern = Page.objects.filter(is_pattern=True)
    for page in pages_pattern:
	match = re.match(page.url, path)
	if match and match.start()==0 and match.end()==len(path):
	    return [page]
    return None